package com.wind.databasecreater;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.util.EncodingUtils;

import com.wind.bean.LatBean;
import com.wind.bean.SqlDatabean;
import com.wind.sql.DBManager;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener {
	Button btn1, btn2, btn3;
	TextView tv1;
	String TAG = "DBCreater";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		btn1 = (Button) findViewById(R.id.button1);
		btn2 = (Button) findViewById(R.id.button2);
		btn3 = (Button) findViewById(R.id.button3);
		tv1 = (TextView) findViewById(R.id.textView1);
		tv1.setText("特别");
		btn1.setOnClickListener(this);
		btn2.setOnClickListener(this);
		btn3.setOnClickListener(this);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	String test = "Region#1|Number#35|119.280381#26.163394|119.280474"
			+ "#26.163436|119.280647#26.163222|119.280794#26.162984|"
			+ "Center#119.279776#26.162105";
	final String spliStr1 = "\\|";
	final String spliStr2 = "#";

	private SqlDatabean test() {

		SqlDatabean sqlBean = buildSqlDataBean(test);
		tv1.setText(showSqlBean(sqlBean).toString());
		return sqlBean;

	}

	/**
	 * 
	 * @param dataStr
	 *            String test =
	 *            "Region#1|Number#35|119.280381#26.163394|119.280474" +
	 *            "#26.163436|119.280647#26.163222|119.280794#26.162984|" +
	 *            "Center#119.279776#26.162105";
	 * @return
	 */
	private SqlDatabean buildSqlDataBean(String dataStr) {
		final String spliStr1 = "\\|";
		final String spliStr2 = "#";
		// StringBuilder total = getFromAssets("filedata");
		// String spliStr = "Region#";
		// ArrayList<String> regions = getSplitedArray(total, spliStr);
		SqlDatabean sqlBean = new SqlDatabean();
		String[] strs = dataStr.split(spliStr1);
		String[] subStr = null;
		ArrayList<LatBean> lats = new ArrayList<LatBean>();
		LatBean tempLat = new LatBean();
		for (int i = 0; i < strs.length; i++) {
			subStr = strs[i].split(spliStr2);
			// Log.d(TAG, strs[i]);
			if (strs[i].startsWith("Region")) {
				// Log.d(TAG, strs[i]);
				sqlBean.setRegion(Integer.parseInt(subStr[1]));
			} else if (strs[i].startsWith("Number")) {
				sqlBean.setNumber(Integer.parseInt(subStr[1]));
			} else if (strs[i].startsWith("Center")) {
				tempLat = new LatBean();
				tempLat.setLatitude(Double.parseDouble(subStr[2]));
				tempLat.setLongitude(Double.parseDouble(subStr[1]));
				sqlBean.setCenter(tempLat);
			} else {
				Log.d(TAG, strs[i]);
				tempLat = new LatBean();
				tempLat.setLatitude(Double.parseDouble(subStr[1]));
				tempLat.setLongitude(Double.parseDouble(subStr[0]));
				lats.add(tempLat);
			}
		}
		sqlBean.setLats(lats);
		// tv1.setText(showSqlBean(sqlBean).toString());
		return sqlBean;

	}

	// lineroad--left--latitude=26.166545596686845longitude=119.28525187075138
	// maproad--right--latitude=26.166426434012426longitude=119.28613565862177
	// lineroad--down--latitude=26.167014422390587longitude=119.28485054522753
	// maproad--up-- latitude=26.1671609676507 longitude=119.28486060351133
	double fixLat = -0.00012d + 0.00015d;
	double fixlong = 0.00088d + 0.00001d;

	/**
	 * 生产重复将ArrayList<SqlDatabean>导入进行添加
	 * 
	 * @param regions
	 *            Region#1|Number#35|119.280381#26.163394|119.280474" +
	 *            "#26.163436|119.280647#26.163222|119.280794#26.162984|" +
	 *            "Center#119.279776#26.162105
	 * @param center
	 *            1#x5100100101040#15900.23#0#0.01#119.2722#26.1744
	 * @return
	 */
	private ArrayList<SqlDatabean> buildSqlDataBean(
			ArrayList<SqlDatabean> beanArray, String regions, String center) {
		final String spliStr1 = "\\|";
		final String spliStr2 = "#";
		// StringBuilder total = getFromAssets("filedata");
		// String spliStr = "Region#";
		// ArrayList<String> regions = getSplitedArray(total, spliStr);
		String[] strsCenter = center.split(spliStr2);
		String[] strsRegion = regions.split(spliStr1);
		String[] subStrRegion = null;
		SqlDatabean sqlBean = new SqlDatabean();
		ArrayList<LatBean> lats = new ArrayList<LatBean>();
		LatBean tempLat = new LatBean();
		sqlBean.setRegion(Integer.parseInt(strsCenter[0]));
		sqlBean.setMarkString(strsCenter[1]);
		sqlBean.setSqrtString(strsCenter[2]);
		sqlBean.setOtherString1(strsCenter[3]);
		sqlBean.setOtherString2(strsCenter[4]);
		tempLat.setLatitude(Double.parseDouble(strsCenter[6]) + fixLat);
		tempLat.setLongitude(Double.parseDouble(strsCenter[5]) + fixlong);
		sqlBean.setCenter(tempLat);
		subStrRegion = strsRegion[0].split(spliStr2);
		if (subStrRegion[1].equals("1")) {
			for (int i = 2; i < strsRegion.length; i++) {
				if (!strsRegion[i].startsWith("Center")) {
					subStrRegion = strsRegion[i].split(spliStr2);
					// Log.d(TAG, strs[i]);
					Log.d(TAG, strsRegion[i]);
					tempLat = new LatBean();
					tempLat.setLatitude(Double.parseDouble(subStrRegion[1])
							+ fixLat);
					tempLat.setLongitude(Double.parseDouble(subStrRegion[0])
							+ fixlong);
					lats.add(tempLat);
				}

			}
			sqlBean.setLats(lats);
			beanArray.add(sqlBean);
		} else {
			subStrRegion = strsRegion[1].split(spliStr2);
			int pointNumber = Integer.parseInt(subStrRegion[1]);
			for (int i = 2; i < 2 + pointNumber; i++) {
				if (!strsRegion[i].startsWith("Center")) {
					subStrRegion = strsRegion[i].split(spliStr2);
					// Log.d(TAG, strs[i]);
					Log.d(TAG, strsRegion[i]);
					tempLat = new LatBean();
					tempLat.setLatitude(Double.parseDouble(subStrRegion[1])
							+ fixLat);
					tempLat.setLongitude(Double.parseDouble(subStrRegion[0])
							+ fixlong);
					lats.add(tempLat);
				}
			}
			sqlBean.setLats(lats);
			beanArray.add(sqlBean);

			sqlBean = new SqlDatabean();
			lats = new ArrayList<LatBean>();
			tempLat = new LatBean();
			sqlBean.setRegion(Integer.parseInt(strsCenter[0]));
			sqlBean.setMarkString(strsCenter[1]);
			sqlBean.setSqrtString(strsCenter[2]);
			sqlBean.setOtherString1(strsCenter[3]);
			sqlBean.setOtherString2(strsCenter[4]);
			tempLat.setLatitude(Double.parseDouble(strsCenter[6]) + fixLat);
			tempLat.setLongitude(Double.parseDouble(strsCenter[5]) + fixlong);
			sqlBean.setCenter(tempLat);
			for (int i = 3 + pointNumber; i < strsRegion.length; i++) {
				if (!strsRegion[i].startsWith("Center")) {
					subStrRegion = strsRegion[i].split(spliStr2);
					// Log.d(TAG, strs[i]);
					Log.d(TAG, strsRegion[i]);
					tempLat = new LatBean();
					tempLat.setLatitude(Double.parseDouble(subStrRegion[1])
							+ fixLat);
					tempLat.setLongitude(Double.parseDouble(subStrRegion[0])
							+ fixlong);
					lats.add(tempLat);
				}
			}
			sqlBean.setLats(lats);
			beanArray.add(sqlBean);

		}
		return beanArray;
	}

	private StringBuilder showSqlBean(SqlDatabean sqlBean) {
		StringBuilder sb = new StringBuilder();
		sb.append("Region=");
		sb.append(sqlBean.getRegion());
		sb.append("\n");
		sb.append("number=");
		sb.append(sqlBean.getNumber());
		sb.append("\n");
		sb.append("getSqrtString=");
		sb.append(sqlBean.getSqrtString());
		sb.append("\n");
		sb.append("getMarkString=");
		sb.append(sqlBean.getMarkString());
		sb.append("\n");
		sb.append("getOtherString1=");
		sb.append(sqlBean.getOtherString1());
		sb.append("\n");
		sb.append("getOtherString2=");
		sb.append(sqlBean.getOtherString2());
		sb.append("\n");
		try {
			sb.append("Center:");
			sb.append("lat=" + sqlBean.getCenter().getLatitude() + "long="
					+ sqlBean.getCenter().getLongitude());
			sb.append("\n");
		} catch (Exception e) {
			sb = new StringBuilder();
			return sb.append("Center无数值");
		}

		ArrayList<LatBean> lats = sqlBean.getLats();
		sb.append("lats:\n");
		for (LatBean latBean : lats) {
			sb.append("lat=" + latBean.getLatitude() + "long="
					+ latBean.getLongitude());
			sb.append("\n");
		}
		return sb;
	}

	/**
	 * 依据spliStr分割test//获得每一个Region
	 * 
	 * @param test
	 * @param spliStr
	 * @return
	 */
	private ArrayList<String> getSplitedArray(StringBuilder test, String spliStr) {
		ArrayList<String> regions = new ArrayList<String>();
		int start = 0;
		int index = -1;
		String str = null;
		while ((index = test.indexOf(spliStr, start + 1)) != -1) {
			str = test.substring(start, index);
			regions.add(str);
			start = index;
			// Log.d(TAG, str + ",start=" + start + ",index=" + index);
		}
		str = test.substring(start, test.length());
		regions.add(str);
		// Log.d(TAG, str + ",start=" + start + ",index=" + index);
		return regions;
	}

	public static final String ENCODING = "UTF-8";

	// 从assets 文件夹中获取文件并读取数据
	public StringBuilder getFromAssetsAll(String fileName) {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		String back = null;
		int totalLeng = 0;
		int duan = 0;
		StringBuilder total = new StringBuilder();
		try {
			InputStream in = getResources().getAssets().open(fileName);
			// 创建byte数组
			byte[] buffer = new byte[128];
			// 获取文件的字节数
			int lenght;
			// 将文件中的数据读到byte数组中
			while ((lenght = in.read(buffer)) != -1) {
				totalLeng += lenght;
				duan++;
				back = EncodingUtils.getString(buffer, 0, lenght, ENCODING);
				total.append(back);
				// Log.d(TAG, back);
				outputStream.write(buffer, 0, lenght);
			}
			// in.close();
			// outputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		Log.d(TAG, "totalLeng=" + totalLeng + ",duan=" + duan + ",total.lenth="
				+ total.length());
		return total;
		// return outputStream.toString();
	}

	public void readArray(String fileName) {
		ArrayList<String> total = getFromAssetsLine(fileName);
		StringBuilder sb = new StringBuilder();
		for (String string : total) {
			sb.append(string);
			sb.append("\n");
		}
		tv1.setText(sb.toString());
	}

	// 从assets 文件夹中获取文件并读取数据
	public ArrayList<String> getFromAssetsLine(String fileName) {
		// ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		String back = null;
		int totalLeng = 0;
		int duan = 0;
		ArrayList<String> total = new ArrayList<String>();
		try {
			BufferedReader bin = new BufferedReader(new InputStreamReader(
					getResources().getAssets().open(fileName)));
			// 创建byte数组
			// 获取文件的字节数
			String str;
			// 将文件中的数据读到byte数组中
			while ((str = bin.readLine()) != null) {
				// totalLeng += lenght;
				// duan++;
				// back = EncodingUtils.getString(buffer, 0, lenght, ENCODING);
				total.add(str);
				// Log.d(TAG, back);
				// outputStream.write(buffer, 0, lenght);
			}
			// in.close();
			// outputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		Log.d(TAG, "totalLeng=" + totalLeng + ",duan=" + duan + ",total.lenth="
				+ total.size());
		return total;
		// return outputStream.toString();
	}

	// 从assets 文件夹中获取文件并读取数据
	public String getFromAssetsBasic(String fileName) {
		String result = "";
		try {
			InputStream in = getResources().getAssets().open(fileName);
			// 获取文件的字节数
			int lenght = in.available();
			Log.d(TAG, "lenght=" + lenght);
			// 创建byte数组
			byte[] buffer = new byte[lenght];
			// 将文件中的数据读到byte数组中
			in.read(buffer);
			result = EncodingUtils.getString(buffer, ENCODING);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * copy asset to db
	 * 
	 * @param dbname
	 *            目标数据库名称
	 * @return size
	 */
	private long copyDBFromAsset(String dbname) {
		String path = this.getDir("", MODE_PRIVATE).getParent() + "/databases";
		String dbpath = path + "/" + dbname;
		File file = new File(path);
		if (!file.exists()) {
			file.mkdir();
		}
		long copySizes = 0;
		try {
			BufferedInputStream bin = new BufferedInputStream(getAssets().open(
					"SQLTotal.db"));
			BufferedOutputStream bout = new BufferedOutputStream(
					new FileOutputStream(new File(dbpath)));
			int b = 0, i = 0;
			while ((b = bin.read()) != -1) {
				bout.write(b);
				i++;
			}
			bout.flush();
			bin.close();
			bout.close();
			copySizes = i;

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return copySizes;
	}

	ArrayList<SqlDatabean> beanArray;

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.button1:
			SqlDatabean bean = DBManager.getInstance().searchDB(1, 20);
			tv1.setText(showSqlBean(bean).toString());
			break;
		case R.id.button2:
			// Log.d(TAG, DataUtils.getNumber() + "");
			// test();
			// readArray("center");
			StringBuilder sbAll = getFromAssetsAll("filedataoriv2");
			String spliStr = "Region#";
			ArrayList<String> regions = getSplitedArray(sbAll, spliStr);
			ArrayList<String> center = getFromAssetsLine("center");
			if (regions.size() == center.size()) {
				beanArray = new ArrayList<SqlDatabean>();
				// SqlDatabean tempBean = null;
				for (int i = 0; i < regions.size(); i++) {
					beanArray = buildSqlDataBean(beanArray, regions.get(i),
							center.get(i));
					// beanArray.add(tempBean);
				}
				tv1.setText(showSqlBean(beanArray.get(0)));
				// tv1.setText(beanArray.size()+"");
			} else {
				tv1.setText("regions=" + regions.size() + "center"
						+ center.size());
			}
			break;
		case R.id.button3:
			if (beanArray.size() == 276) {
				DBManager.getInstance().insertSqlDataArray(beanArray);
				tv1.setText(beanArray.size() + "");
			}
			break;

		default:
			break;
		}
	}

}
